package com.example.echoewish.ui.main_activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.echoewish.pojo.PartPost;
import com.example.echoewish.ui.home_activity.PostDetailActivity;
import com.example.echoewish.R;
import com.example.echoewish.custom_compose.RefreshListView;
import com.example.echoewish.econstant.Constant;
import com.example.echoewish.util.DataGenerator;
import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;

import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {

    private View view=null;
    private final static  int CHANGE_LIST_VIEW=3;
    private final static  int NO_CHANGE_LIST_VIEW=4;

    TabLayout topTabLayout;
    RefreshListView partPostListView;
    TextView homeSearchEditText;
    Button homeSearchDeleteButton;
    Button homeSearchButton;
    private PartPostAdapter partPostAdapter;

    private HomeViewModel homeViewModel=null;


    private Handler homefragmentHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case  Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE:
                    if(msg.arg1==CHANGE_LIST_VIEW)
                    {
                        partPostAdapter.clear();
                        partPostAdapter.addAll(homeViewModel.partPostMutableLiveData.getValue());
                        partPostAdapter.notifyDataSetChanged();
                    }
                    else if(msg.arg1==NO_CHANGE_LIST_VIEW)
                        if (getActivity()!=null)
                        Toast.makeText(getActivity(),"没有更多了",Toast.LENGTH_SHORT).show();
                    break;
                case  Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE:
                    if (getActivity()!=null)
                    Toast.makeText(getActivity(),"网络错误，请检测网络",Toast.LENGTH_SHORT).show();
                    break;
            }
            partPostListView.reflashComplete();
        }
    };

    public HomeFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != view){
            ViewGroup parent = (ViewGroup) view.getParent();
            if (null != parent) {
                parent.removeView(view);
            }
        }else {
            view = inflater.inflate(R.layout.fragment_home,container,false);
            initView(view);
        }
        observeLiveData();
        return view;
    }


    public void initView(@NotNull View view)
    {
        topTabLayout=view.findViewById(R.id.home_top_tab_layout);
        partPostListView=view.findViewById(R.id.home_part_post_listview);
        homeSearchEditText=view.findViewById(R.id.home_search_edit_text);
//        homeSearchDeleteButton=view.findViewById(R.id.home_search_delete_button);
//        homeSearchButton=view.findViewById(R.id.home_search_button);

        //初始化顶部选择栏
        for(int i = 0; i<DataGenerator.myTopTab.length;++i)
            topTabLayout.addTab(topTabLayout.newTab().setText(DataGenerator.myTopTab[i]));
        topTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                itemSelected(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //初始化滚动区域
        partPostAdapter=new PartPostAdapter(getActivity(),R.layout.part_post_layout,new LinkedList<>());
        partPostListView.setAdapter(partPostAdapter);

        partPostListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(getActivity(), PostDetailActivity.class);
                System.out.println(position-1);
                intent.putExtra("postId",homeViewModel.partPostMutableLiveData.getValue().get(position-1).postId);
                startActivity(intent);
            }
        });

        //添加监听器
//        homeSearchDeleteButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                searchClear();
//                itemSelected(homeViewModel.zoneMutableLiveData.getValue());
//            }
//        });

        partPostListView.setInterface(new RefreshListView.IReflashListener() {
            @Override
            public void onReflash() {
                int k=homeViewModel.partPostMutableLiveData.getValue().size();
                homeViewModel.startMutableLiveData.setValue(k);
            }
        });

//        homeSearchButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                homeViewModel.keywordMutableLiveData.setValue(homeSearchEditText.getText().toString());
//            }
//        });

        homeSearchEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(HomeFragment.this.getActivity(),SearchContentActivity.class);
                startActivity(intent);
            }
        });



        initViewModel();
        homeViewModel.startMutableLiveData.setValue(0);
    }

    private void initViewModel()
    {
        homeViewModel=new ViewModelProvider(getActivity(),new ViewModelProvider.AndroidViewModelFactory(getActivity().getApplication())).get(HomeViewModel.class);
    }

    private void observeLiveData()
    {
        homeViewModel.newPartPostMutableLiveData.observe(this, new Observer<List<PartPost>>() {
            @Override
            public void onChanged(List<PartPost> partPosts) {
                if(partPosts==null) {
                    Message message=new Message();
                    message.what=Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE;
                    homefragmentHandler.sendMessage(message);
                    homeViewModel.debugMutableLiveData.setValue(homeViewModel.startMutableLiveData.getValue());
                    return;
                }
                if (homeViewModel.startMutableLiveData.getValue()==homeViewModel.debugMutableLiveData.getValue())
                {
                    partPostListView.reflashComplete();
                    return;
                }
                homeViewModel.debugMutableLiveData.setValue(homeViewModel.startMutableLiveData.getValue());

                Message message=new Message();
                message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                if(partPosts.size()!=0)
                {
                    homeViewModel.partPostMutableLiveData.getValue().addAll(partPosts);
                    message.arg1= CHANGE_LIST_VIEW;
                }
                else
                    message.arg1=NO_CHANGE_LIST_VIEW;
                homefragmentHandler.sendMessage(message);
            }
        });

        homeViewModel.keywordMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(homeViewModel.debugkeywordMutableLiveData.getValue().equals(homeViewModel.keywordMutableLiveData.getValue())) {
                    return;
                }
                homeViewModel.debugMutableLiveData.setValue(-1);
                homeViewModel.partPostMutableLiveData.setValue(new LinkedList<>());
                partPostAdapter.clear();
                partPostAdapter.addAll(homeViewModel.partPostMutableLiveData.getValue());
                partPostAdapter.notifyDataSetChanged();
                homeViewModel.debugkeywordMutableLiveData.setValue(s);
                homeViewModel.getPartPostMessageByKeyWord();
            }
        });

        homeViewModel.startMutableLiveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                homeViewModel.getPartPostMessage();

            }
        });



    }

    private void searchClear()
    {
        homeViewModel.debugkeywordMutableLiveData.setValue("");
        homeViewModel.keywordMutableLiveData.setValue("");
    }

    public void itemSelected(int position)
    {
        homeViewModel.partPostMutableLiveData.setValue(new LinkedList<>());
        partPostAdapter.clear();
        partPostAdapter.addAll(homeViewModel.partPostMutableLiveData.getValue());
        partPostAdapter.notifyDataSetChanged();
        switch(position)
        {
            case 0:
                homeViewModel.zoneMutableLiveData.setValue(0);
                break;
            case 1:
                homeViewModel.zoneMutableLiveData.setValue(1);
                break;
            case 2:
                homeViewModel.zoneMutableLiveData.setValue(2);
                break;
            case 3:
                homeViewModel.zoneMutableLiveData.setValue(3);
                break;
            case 4:
                homeViewModel.zoneMutableLiveData.setValue(4);
                break;
            case 5:
                homeViewModel.zoneMutableLiveData.setValue(5);
                break;
        }
        homeViewModel.debugMutableLiveData.setValue(-1);
        homeViewModel.startMutableLiveData.setValue(0);
        searchClear();
    }


}